import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;

import test.fairway.IS3CredentialGetter;
import test.fairway.LocalS3CrentialGetter;
import test.fairway.S3Client;
import test.fairway.S3Operation;
import test.fairway.S3Permission;
import test.fairway.S3SessionCredential;

public class S3Sample {

	public static void main(String[] args) throws IOException {
		String bucket = "fairway-test";
		IS3CredentialGetter credentialGetter = new LocalS3CrentialGetter();

		List<S3Permission> permissions = new ArrayList<S3Permission>();
		permissions.add(new S3Permission(S3Operation.ListObject));
		permissions.add(new S3Permission(S3Operation.UploadObject, "test1.txt", "test2.txt"));
		permissions.add(new S3Permission(S3Operation.DownloadObject, "*"));
		permissions.add(new S3Permission(S3Operation.DeleteObject, "test2.txt"));
		S3SessionCredential credential = credentialGetter.getS3Crential("fairway", bucket, 900, permissions);
		try {
			S3Client s3 = new S3Client(credential, bucket);
			List<String> objects = s3.getObjectList();
			for (String object : objects) {
				System.out.println(object);
			}
			
			URL url = s3.getDownloadUrl("test2.txt");
			System.out.println(url.toString());
			
			s3.deleteObject("test2.txt");
//			Map<String, String> metadata = new HashMap<String, String>();
//			metadata.put("project", "X-A");
//			s3.uploadObject("test2.txt", new File("/Users/corei7/.vimrc"), metadata);
			
//			Map<String, String> metadata = null;
//			File outputfile = new File("test.txt");
//			metadata = s3.downloadObject("test2.txt", new FileOutputStream(outputfile));
//			for (Map.Entry<String, String> entry : metadata.entrySet()) {
//				System.out.println(entry.getKey() + ": " + entry.getValue());
//			}
			
		} catch (AmazonServiceException ase) {
			System.out.println("Caught an AmazonServiceException, which means your request made it "
					+ "to Amazon S3, but was rejected with an error response for some reason.");
			System.out.println("Error Message:    " + ase.getMessage());
			System.out.println("HTTP Status Code: " + ase.getStatusCode());
			System.out.println("AWS Error Code:   " + ase.getErrorCode());
			System.out.println("Error Type:       " + ase.getErrorType());
			System.out.println("Request ID:       " + ase.getRequestId());
		} catch (AmazonClientException ace) {
			System.out.println("Caught an AmazonClientException, which means the client encountered "
					+ "a serious internal problem while trying to communicate with S3, "
					+ "such as not being able to access the network.");
			System.out.println("Error Message: " + ace.getMessage());
		}
	}

}
